#!/bin/bash
# Copyright (c) 2024 maminjie <canpool@163.com>
# SPDX-License-Identifier: MulanPSL-2.0

usage() {
printf "Display capabilities that the package provides is required by

usage:
    bash rpm_requiredby.sh [-h | --help] [PACKAGES | PKGFILE] [FILTER]

arguments:
    PACKAGE        rpm package name
    PKGFILE        file include rpm package name
    FILTER         filter content, such as: 3.9.9-30

optional arguments:
    -h, --help     show the help message and exit
\n"
}

get_list() {
    local lst=""

    if [ -f "$1" ]; then
        lst=$(cat $1)
    else
        lst=$1
    fi

    echo $lst
}


main() {
    if [[ $# -lt 1 || "$1" = "-h" || "$1" = "--help" ]]; then
        usage; exit 1
    fi
    local pkgs=$(get_list "$1")
    local filter="$2"
    OLD_IFS="$IFS"
    IFS=$'\n'
    echo "BasePackage,Type,Symbol,RequiredByPackage,From,SRPM"
    for pkg in $pkgs; do
        local pros=$(dnf repoquery -q --provides "$pkg")
        if [ -n "$filter" ]; then
            pros=$(echo "$pros" | grep "$filter")
        fi
        for pro in $pros; do
            local wreqs=$(dnf repoquery -q --whatrequires "$pro")
            for req in $wreqs; do
                local req_type="install"
                if [[ $req =~ src$ ]]; then
                    req_type="build"
                fi
                dnf repoquery -q --requires "$req" | grep -q "$pro"
                if [ $? -ne 0 ]; then
                    continue
                fi
                local info=$(dnf repoquery -q -i $req)
                local src_name="$req"
                if [ $req_type == "install" ]; then
                    src_name=$(echo "$info" | grep -E "^Source.*\.src\.rpm$" | head -n1 | awk '{print $NF}')
                fi
                src_name=$(echo $src_name | sed -r 's/-[^-]+-[^-]+$//')
                local from_repo=$(echo "$info" | grep -E "^Repository" | head -n1 | awk '{print $NF}')
                echo "$pkg,$req_type,$pro,$req,$from_repo,$src_name"
            done
        done
    done
    IFS="$OLD_IFS"
}

main "$@"
